<template>
  <div class="advanced-filter">
    <!-- 筛选条件区域 -->
    <div class="filter-fields">
      <div 
        class="filter-row" 
        v-for="(row, rowIndex) in visibleFields" 
        :key="rowIndex"
      >
        <div 
          class="filter-item" 
          v-for="(field, fieldIndex) in row" 
          :key="fieldIndex"
          :style="{ width: `calc(100% / ${row.length} - 16px)` }"
        >
          <label 
            v-if="field.label" 
            class="filter-label"
            :class="{ 'required': field.required }"
          >
            {{ field.label }}
            <span v-if="field.required" class="required-mark">*</span>
          </label>
          
          <!-- 文本输入框 -->
          <el-input
            v-if="field.type === 'input'"
            v-model="filterValues[field.key]"
            :placeholder="field.placeholder || `请输入${field.label}`"
            :disabled="field.disabled"
            :clearable="field.clearable !== false"
            :maxlength="field.maxlength"
            :show-word-limit="field.showWordLimit"
            @input="handleInput(field.key, $event)"
          />
          
          <!-- 下拉选择框（支持可输入） -->
          <el-select
            v-if="field.type === 'select'"
            v-model="filterValues[field.key]"
            :placeholder="field.placeholder || `请选择${field.label}`"
            :disabled="field.disabled"
            :clearable="field.clearable !== false"
            :filterable="field.filterable"      
            :allow-create="field.allowCreate"  
            :multiple="field.multiple"
            :collapse-tags="field.collapseTags"
            :remote="field.remote"             
            :remote-method="field.remoteMethod"
            @change="handleChange(field.key, $event)"
          >
            <el-option
              v-for="option in field.options || []"
              :key="option.value"
              :label="option.label"
              :value="option.value"
              :disabled="option.disabled"
            />
          </el-select>
          
          <!-- 日期选择器 -->
          <el-date-picker
            v-if="field.type === 'date'"
            v-model="filterValues[field.key]"
            :placeholder="field.placeholder || `请选择${field.label}`"
            :disabled="field.disabled"
            :format="field.format || 'YYYY-MM-DD'"
            :value-format="field.valueFormat || 'YYYY-MM-DD'"
            :clearable="field.clearable !== false"
            @change="handleChange(field.key, $event)"
          />
          
          <!-- 日期范围选择器 -->
          <el-date-picker
            v-if="field.type === 'dateRange'"
            v-model="filterValues[field.key]"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="field.disabled"
            :format="field.format || 'YYYY-MM-DD'"
            :value-format="field.valueFormat || 'YYYY-MM-DD'"
            :clearable="field.clearable !== false"
            @change="handleChange(field.key, $event)"
          />
          
          <!-- 数字输入框 -->
          <el-input-number
            v-if="field.type === 'number'"
            v-model="filterValues[field.key]"
            :placeholder="field.placeholder || `请输入${field.label}`"
            :disabled="field.disabled"
            :min="field.min"
            :max="field.max"
            :step="field.step || 1"
            :precision="field.precision"
            @change="handleChange(field.key, $event)"
          />
          
          <!-- 开关 -->
          <el-switch
            v-if="field.type === 'switch'"
            v-model="filterValues[field.key]"
            :disabled="field.disabled"
            :active-text="field.activeText"
            :inactive-text="field.inactiveText"
            @change="handleChange(field.key, $event)"
          />
          
          <!-- 复选框 -->
          <el-checkbox
            v-if="field.type === 'checkbox'"
            v-model="filterValues[field.key]"
            :disabled="field.disabled"
            :label="field.checkboxLabel"
            @change="handleChange(field.key, $event)"
          />
        </div>
      </div>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="filter-actions">
      <el-button 
        type="primary" 
        @click="handleQuery"
        :loading="loading"
      >
        查询
      </el-button>
      <el-button 
        @click="handleReset"
        :disabled="loading"
      >
        重置
      </el-button>
      
      <el-button 
        v-if="hasMoreFields"
        type="text" 
        @click="toggleExpand"
      >
        {{ isExpanded ? '收起' : '更多' }}
        <i class="el-icon-arrow-up" v-if="isExpanded"></i>
        <i class="el-icon-arrow-down" v-else></i>
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';

// 定义筛选字段的类型
type FilterFieldType = 'input' | 'select' | 'date' | 'dateRange' | 'number' | 'switch' | 'checkbox';

// 下拉选项类型
interface SelectOption {
  label: string;
  value: string | number | boolean;
  disabled?: boolean;
}

// 筛选字段配置接口
interface FilterField {
  key: string; // 字段标识
  label: string; // 字段标签
  type: FilterFieldType; // 字段类型
  required?: boolean; // 是否必填
  placeholder?: string; // 占位文本
  disabled?: boolean; // 是否禁用
  clearable?: boolean; // 是否可清除
  defaultValue?: any; // 默认值
  
  // 针对select类型（使用Element原生属性）
  options?: SelectOption[]; // 下拉选项
  filterable?: boolean; // 是否可搜索（Element原生）
  allowCreate?: boolean; // 是否允许创建新条目（Element原生）
  multiple?: boolean; // 是否支持多选
  collapseTags?: boolean; // 是否折叠多选标签
  remote?: boolean; // 是否远程搜索
  remoteMethod?: (query: string) => void; // 远程搜索方法
  
  // 针对input类型
  maxlength?: number; // 最大长度
  showWordLimit?: boolean; // 是否显示字数统计
  
  // 针对date和dateRange类型
  format?: string; // 显示格式
  valueFormat?: string; // 绑定值格式
  
  // 针对number类型
  min?: number; // 最小值
  max?: number; // 最大值
  step?: number; // 步长
  precision?: number; // 精度
  
  // 针对switch类型
  activeText?: string; // 激活状态文本
  inactiveText?: string; // 非激活状态文本
  
  // 针对checkbox类型
  checkboxLabel?: string; // 复选框文本
  
  // 布局相关
  span?: number; // 占比，1-24
  hidden?: boolean; // 是否隐藏
  advanced?: boolean; // 是否为高级选项（默认隐藏）
}

// 组件Props
const props = defineProps<{
  fields: FilterField[]; // 筛选字段配置
  inline?: boolean; // 是否 inline 模式
  columns?: number; // 每行显示的列数，默认4
  loading?: boolean; // 加载状态
  defaultValues?: Record<string, any>; // 默认值
}>();

// 组件Emits
const emit = defineEmits<{
  (e: 'query', values: Record<string, any>): void; // 查询事件
  (e: 'reset', values: Record<string, any>): void; // 重置事件
  (e: 'change', key: string, value: any): void; // 字段变化事件
}>();

// 状态管理
const filterValues = ref<Record<string, any>>({});
const isExpanded = ref(false); // 是否展开高级选项

// 初始化筛选值
const initFilterValues = () => {
  const values: Record<string, any> = {};
  
  // 初始化默认值
  props.fields.forEach(field => {
    // 优先使用defaultValues中的值
    if (props.defaultValues && props.defaultValues[field.key] !== undefined) {
      values[field.key] = props.defaultValues[field.key];
    } 
    // 其次使用字段配置中的defaultValue
    else if (field.defaultValue !== undefined) {
      values[field.key] = field.defaultValue;
    } 
    // 否则根据类型设置默认值
    else {
      switch (field.type) {
        case 'switch':
          values[field.key] = false;
          break;
        case 'checkbox':
          values[field.key] = false;
          break;
        case 'dateRange':
          values[field.key] = [];
          break;
        case 'select':
          values[field.key] = field.multiple ? [] : '';
          break;
        default:
          values[field.key] = '';
      }
    }
  });
  
  filterValues.value = values;
};

// 处理字段输入
const handleInput = (key: string, value: any) => {
  filterValues.value[key] = value;
  emit('change', key, value);
};

// 处理字段变化
const handleChange = (key: string, value: any) => {
  filterValues.value[key] = value;
  emit('change', key, value);
};

// 处理查询
const handleQuery = () => {
  emit('query', { ...filterValues.value });
};

// 处理重置
const handleReset = () => {
  initFilterValues();
  emit('reset', { ...filterValues.value });
};

// 切换展开/收起
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};

// 获取可见的字段（排除隐藏的）
const visibleFields = computed(() => {
  // 过滤掉隐藏的字段
  let visible = props.fields.filter(field => !field.hidden);
  
  // 如果没有展开，过滤掉高级选项
  if (!isExpanded.value) {
    visible = visible.filter(field => !field.advanced);
  }
  
  // 按columns分组，每columns个字段一组
  const columns = props.columns || 4;
  const rows: FilterField[][] = [];
  
  for (let i = 0; i < visible.length; i += columns) {
    rows.push(visible.slice(i, i + columns));
  }
  
  return rows;
});

// 是否有更多字段可以展开/收起
const hasMoreFields = computed(() => {
  return props.fields.some(field => !field.hidden && field.advanced);
});

// 监听默认值变化
watch(
  () => props.defaultValues,
  (newValues) => {
    if (newValues) {
      initFilterValues();
    }
  },
  { deep: true }
);

// 初始化
onMounted(() => {
  initFilterValues();
});

// 暴露方法给父组件
defineExpose({
  // 获取当前筛选值
  getFilterValues: () => ({ ...filterValues.value }),
  // 设置筛选值
  setFilterValues: (values: Record<string, any>) => {
    Object.keys(values).forEach(key => {
      if (filterValues.value.hasOwnProperty(key)) {
        filterValues.value[key] = values[key];
      }
    });
  },
  // 重置筛选条件
  reset: handleReset,
  // 执行查询
  query: handleQuery
});
</script>

<style lang="scss" scoped>
// 混合宏定义
@mixin filter-container {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

@mixin filter-item-base {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.advanced-filter {
  @include filter-container;
}

.filter-fields {
  .filter-row {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -8px 16px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .filter-item {
    @include filter-item-base;
    padding: 0 8px;
    
    .filter-label {
      display: inline-block;
      margin-right: 8px;
      color: #333;
      font-size: 14px;
      white-space: nowrap;
      min-width: 80px;
      
      .required-mark {
        color: #ff4d4f;
        margin-left: 4px;
      }
    }
    
    // 占满剩余空间
    > *:last-child {
      flex: 1;
      min-width: 0;
    }
  }
}

.filter-actions {
  display: flex;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px dashed #e5e6eb;
  
  button {
    margin-right: 8px;
    
    &:last-child {
      margin-left: auto;
      margin-right: 0;
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .filter-item {
    flex-direction: column;
    align-items: flex-start !important;
    
    .filter-label {
      margin-bottom: 8px;
    }
  }
}
</style>